package struts.tools;

import java.io.File;
import java.util.Map;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

import struts.StrutsFactory;
import struts.StrutsPackage;
import struts.WebApp;

public class StrutsSerializer {
	
	public static StrutsSerializer instance;
	public static final String defaultFile = "model/WebApp1.xmi";
	
	private String path;
	private WebApp loadedWebApp;

	public static void main(String[] args){
		StrutsSerializer serial = StrutsSerializer.getInstance();
		
		if(args.length == 0 || args[0].isEmpty())
			serial.setPath(StrutsSerializer.defaultFile);
		else
			serial.setPath(args[0]);
		
		serial.serialize();
	}
	
	public StrutsSerializer(){
		this.instance = this;
	}
	
	public static StrutsSerializer getInstance(){
		if(StrutsSerializer.instance != null){
			return new StrutsSerializer();
		}
		else return StrutsSerializer.instance;
	}
	
	public void serialize(){
		StrutsFactory strutsFactory = StrutsFactory.eINSTANCE;
		File appXMI = new File(this.path);
		
		this.loadedWebApp = load(appXMI);
		
	}
	
	public WebApp load(File f) {
		ResourceSet rs = new ResourceSetImpl();
		Resource.Factory.Registry registry =
				rs.getResourceFactoryRegistry();
		Map<String,Object> m = registry.getExtensionToFactoryMap();
		m.put("xmi", new XMIResourceFactoryImpl());
		rs.getPackageRegistry().put(StrutsPackage.eNS_URI,
				StrutsPackage.eINSTANCE);
		URI uri = URI.createFileURI(f.getAbsolutePath());
		Resource resource = rs.getResource(uri, true);
		if (resource.isLoaded() && resource.getContents().size() > 0) {
			return (WebApp) resource.getContents().get(0);
		}
		return null;
	}
	
	public String getPath(){
		return this.path;
	}
	
	public void setPath(String path){
		this.path = path;
	}
	
}
